package com.chinamobile.maps.action;

import java.io.PrintWriter;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.chinamobile.maps.dao.IGridDAO;
import com.chinamobile.maps.dao.IRegionsDAO;
import com.chinamobile.maps.orm.Grid;
import com.chinamobile.maps.orm.RegionModel;
import com.chinamobile.maps.orm.Regions;
import com.chinamobile.maps.util.JsonUtil;
import com.chinamobile.maps.util.LoggerUtil;
import com.chinamobile.maps.util.Struts2Util;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @ClassName:   RegionsAction
 * @Description: TODO
 * @author:      frankwong
 * @date:        2012-9-26 下午10:14:57
 *
 */
public class RegionsAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = -374789727959530071L;
	
	public IRegionsDAO regionDao = null;
	private IGridDAO gridDao = null;
	
	public void getComboxJson(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
            List<Regions> regions = this.regionDao.getObjects("from Regions r where r.parentRegionId is null or r.parentRegionId = 1");
            StringBuilder json= new StringBuilder();
            json.append("[");
            for(Regions region:regions){
            	json.append("{\"id\":"+region.getId()+","+"\"name\""+":\""+region.getName()+"\"},");
            }
            json.delete(json.length()-1, json.length());
            json.append("]");
            out.print(json.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	
	public void getMicroRegionComboxJson(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			Integer regionId = Integer.parseInt(request.getParameter("id"));
            List<Regions> regions = this.regionDao.getObjects("from Regions r where  r.parentRegionId = "+regionId);
            StringBuilder json= new StringBuilder();
            json.append("[");
            for(Regions region:regions){
            	json.append("{\"id\":"+region.getId()+","+"\"name\""+":\""+region.getName()+"\"},");
            }
            json.delete(json.length()-1, json.length());
            json.append("]");
            out.print(json.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	public void getMicroRegionTreeJson(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			Integer regionId = Integer.parseInt(request.getParameter("id"));
			List<Regions> regions = this.regionDao.getObjects("from Regions r where r.parentRegionId = "+regionId);
			StringBuilder sb = new StringBuilder();
			int hallCount ;
            int mobileHallCount ;
            int chanelCount ;
            double hallPercent ;
            DecimalFormat df = new DecimalFormat("0.00%");
            String hallPercentStr ;
            String chnelPercent = "100%";
            String jsonTop;
            String jsonStr;
			int count  = regions.size();
			sb.append("[");
			for(int i = 0;i<count;i++){
				hallCount = regions.get(i).getMainHallCount()+regions.get(i).getCooperativeHallCount()+regions.get(i).getUnicomHallCount()+regions.get(i).getTelecomHallCount();
	            mobileHallCount = regions.get(i).getMainHallCount()+regions.get(i).getCooperativeHallCount();
	            chanelCount = regions.get(i).getSpecialAgentCount()+regions.get(i).getVillagePointCount()+regions.get(i).getAuthorizedPointCount()+regions.get(i).getShareChannelCount();
	            if(hallCount != 0){
	            	hallPercent = mobileHallCount*1.00/hallCount;
		            hallPercentStr = df.format(hallPercent);
	            }
	            else{
	            	hallPercentStr = "0%";
	            }
	            String microRegionName = regions.get(i).getName();
	            jsonTop = "{\"id\":"+regions.get(i).getId()+",\"text\":\""+microRegionName+"\",\"state\" : \"closed\",\"children\":[";
	            jsonStr = "{\"text\" : \"营业厅("+hallCount+")\",\"state\" : \"open\",\"children\" : [{\"text\" : \"移动营业厅("+mobileHallCount+",市场份额:"+hallPercentStr+")\",\"children\" : [{\"text\" : \"移动主厅("+regions.get(i).getMainHallCount()+")\",\"attributes\":\""+microRegionName+"Z移动主厅"+"\"}, {\"text\" : \"移动合作厅("+regions.get(i).getCooperativeHallCount()+")\",\"attributes\":\""+microRegionName+"Z移动合作厅"+"\"}]}, {\"text\" : \"联通营业厅("+regions.get(i).getUnicomHallCount()+")\",\"attributes\":\""+microRegionName+"Z联通营业厅"+"\"}, {\"text\" : \"电信营业厅("+regions.get(i).getTelecomHallCount()+")\",\"attributes\":\""+microRegionName+"Z电信营业厅"+"\"}]}, {\"text\" : \"渠道("+chanelCount+",排他渠道份额: "+chnelPercent+")\",\"state\" :\"open\",\"children\" : [{\"text\" : \"特约代理店("+regions.get(i).getSpecialAgentCount()+")\",\"attributes\":\""+microRegionName+"Z特约代理店"+"\"}, {\"text\" : \"授权销售点("+regions.get(i).getAuthorizedPointCount()+")\",\"attributes\":\""+microRegionName+"Z授权销售点"+"\"}, {\"text\" : \"村级便民点("+regions.get(i).getVillagePointCount()+")\",\"attributes\":\""+microRegionName+"Z村级便民点"+"\"}, {\"text\" : \"共享渠道("+regions.get(i).getShareChannelCount()+")\",\"attributes\":\""+microRegionName+"Z共享渠道"+"\"}]}]},";
	            sb.append(jsonTop);
	            sb.append(jsonStr);
			}
			sb.delete(sb.length()-1, sb.length());
			sb.append("]");
            out.print(sb.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
		
		
	}
	public void getRegionTreeJson(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			Integer regionId = Integer.parseInt(request.getParameter("id"));
            Regions region = this.regionDao.getRegionsById(regionId);
            int hallCount = region.getMainHallCount()+region.getCooperativeHallCount()+region.getUnicomHallCount()+region.getTelecomHallCount();
            int mobileHallCount = region.getMainHallCount()+region.getCooperativeHallCount();
            int chanelCount = region.getSpecialAgentCount()+region.getVillagePointCount()+region.getAuthorizedPointCount()+region.getShareChannelCount();
            double hallPercent = mobileHallCount*1.00/hallCount;
            DecimalFormat df = new DecimalFormat("0.00%");
            String hallPercentStr = df.format(hallPercent);
            String chnelPercent = "100%";
            String jsonStr = "[{\"id\" : 0,\"text\" : \"营业厅("+hallCount+")\",\"state\" : \"open\",\"children\" : [{\"id\" : 0,\"text\" : \"移动营业厅("+mobileHallCount+",市场份额:"+hallPercentStr+")\",\"children\" : [{\"id\" : 1,\"text\" : \"移动主厅("+region.getMainHallCount()+")\"}, {\"id\" : 2,\"text\" : \"移动合作厅("+region.getCooperativeHallCount()+")\"}]}, {\"id\" : 3,\"text\" : \"联通营业厅("+region.getUnicomHallCount()+")\"}, {\"id\" : 4,\"text\" : \"电信营业厅("+region.getTelecomHallCount()+")\"}]}, {\"id\" : 0,\"text\" : \"渠道("+chanelCount+",排他渠道份额: "+chnelPercent+")\",\"state\" :\"open\",\"children\" : [{\"id\" : 5,\"text\" : \"特约代理店("+region.getSpecialAgentCount()+")\"}, {\"id\" : 6,\"text\" : \"授权销售点("+region.getAuthorizedPointCount()+")\"}, {\"id\" : 7,\"text\" : \"村级便民点("+region.getVillagePointCount()+")\"}, {\"id\" : 8,\"text\" : \"共享渠道("+region.getShareChannelCount()+")\"}]}]";
            out.print(jsonStr);
			out.flush();
			out.close();
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	
	public void getGridPathLatLng(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			String data = String.valueOf(request.getParameter("data"));
			String[] strArray = data.split(",");
			HashMap<String,String> hashMap = new HashMap<String,String>();
			int count = strArray.length;
			for(int i = 0;i<count;i++){
				if(strArray[i] != null && !strArray[i].equals("")){
					String[] result = strArray[i].split("Z");
					hashMap.put(result[0], result[0]);
				}
			}
			List<String> gmapLatLng = new ArrayList<String>();
			Iterator iter = hashMap.entrySet().iterator(); 
			while (iter.hasNext()) { 
			    Map.Entry<String,String> entry = (Map.Entry) iter.next(); 
			    String name = entry.getKey(); 
			    Grid grid = this.gridDao.getGridByname(name);
			    List<Regions> resultRegions = this.regionDao.getObjects("from Regions as regions where regions.gridId="+grid.getId());
				if(resultRegions != null || resultRegions.size()!= 0){
					int count1 = resultRegions.size();
					for(int i = 0;i<count1;i++){
						if(resultRegions.get(i).getPath() != null && !resultRegions.get(i).getPath().equals("")){
							gmapLatLng.add(resultRegions.get(i).getPath());
						}
					}
				}
			} 
			
			JSONArray jsonArrayResult = JSONArray.fromObject(gmapLatLng);
			out.print(jsonArrayResult.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	
	public void getRegionPathLatLng(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			String data = String.valueOf(request.getParameter("data"));
			String[] strArray = data.split(",");
			HashMap<String,String> hashMap = new HashMap<String,String>();
			int count = strArray.length;
			for(int i = 0;i<count;i++){
				if(strArray[i] != null && !strArray[i].equals("")){
					String[] result = strArray[i].split("Z");
					hashMap.put(result[0], result[0]);
				}
			}
			List<String> gmapLatLng = new ArrayList<String>();
			Iterator iter = hashMap.entrySet().iterator(); 
			while (iter.hasNext()) { 
			    Map.Entry<String,String> entry = (Map.Entry) iter.next(); 
			    String name = entry.getKey(); 
			    List<Regions> resultRegions = this.regionDao.getObjects("from Regions as regions where regions.name='"+name+"'");
				if(resultRegions != null || resultRegions.size()!= 0){
					gmapLatLng.add(resultRegions.get(0).getPath());
				}
			} 
			
			JSONArray jsonArrayResult = JSONArray.fromObject(gmapLatLng);
			out.print(jsonArrayResult.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	public void savePath(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			Integer microRegionId = Integer.parseInt(request.getParameter("id"));
			String path = request.getParameter("path");
			JSONArray array = JSONArray.fromObject(path);  
			int count = array.size();
			StringBuffer sb = new StringBuffer();
			JSONObject obj;
			for(int i = 0;i<count;i++){
				obj = (JSONObject)array.get(i);
				sb.append(obj.get("Da")+",");
				sb.append(obj.get("Ea")+";");
			}
			String pathResult = sb.substring(0, sb.length()-1);
            Regions region = this.regionDao.getRegionsById(microRegionId);
            region.setPath(pathResult);
            this.regionDao.updateRegions(region);
            out.print("{\"result\":false}");
			out.flush();
			out.close();
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	
	public void getRegionsList(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			int pageNumber = Integer.parseInt((request.getParameter("pageNumber")));
			int pageSize = Integer.parseInt((request.getParameter("pageSize")));
			List<Regions> regionsList =  this.regionDao.getObjects("from Regions r where r.parentRegionId is not null and r.parentRegionId != 1");
			int count;
			if(regionsList == null){
				out.print("[]");
				return;
			}else{
				count = regionsList.size();
				List<RegionModel> regionsResult = new ArrayList<RegionModel>();
				for (int i = pageSize * (pageNumber - 1); i < count
						&& i < pageSize * pageNumber; i++) {
					RegionModel regionModel = new RegionModel();
					regionModel.setId(regionsList.get(i).getId());
					regionModel.setName(regionsList.get(i).getName());
					regionModel.setParentRegionId(regionsList.get(i).getParentRegionId());
					regionsResult.add(regionModel);
				}
				Map<String, Object> jsonMap = new HashMap<String, Object>();
				jsonMap.put("total", count);
				jsonMap.put("rows", regionsResult);
				JSONObject jsonObject = JSONObject.fromObject(jsonMap,JsonUtil.jsonConfig);
				out.print(jsonObject.toString());
				out.flush();
				out.close();
			}
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	
	public void deleteRegion() {
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/json;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			Integer id = Integer.parseInt(request.getParameter("id"));
			Regions region = this.regionDao.getRegionsById(id);
			Regions mainRegion = this.regionDao.getRegionsById(1);
			Regions parentRegion = this.regionDao.getRegionsById(region.getParentRegionId());
			
			mainRegion.setCooperativeHallCount(mainRegion.getCooperativeHallCount()-region.getCooperativeHallCount());
			mainRegion.setAuthorizedPointCount(mainRegion.getAuthorizedPointCount()-region.getAuthorizedPointCount());
			mainRegion.setMainHallCount(mainRegion.getMainHallCount()-region.getMainHallCount());
			mainRegion.setShareChannelCount(mainRegion.getShareChannelCount()-region.getShareChannelCount());
			mainRegion.setSpecialAgentCount(mainRegion.getSpecialAgentCount()-region.getSpecialAgentCount());
			mainRegion.setTelecomHallCount(mainRegion.getTelecomHallCount()-region.getTelecomHallCount());
			mainRegion.setUnicomHallCount(mainRegion.getUnicomHallCount()-region.getUnicomHallCount());
			mainRegion.setVillagePointCount(mainRegion.getVillagePointCount()-region.getVillagePointCount());
			this.regionDao.updateRegions(mainRegion);
			
			parentRegion.setCooperativeHallCount(parentRegion.getCooperativeHallCount()-region.getCooperativeHallCount());
			parentRegion.setAuthorizedPointCount(parentRegion.getAuthorizedPointCount()-region.getAuthorizedPointCount());
			parentRegion.setMainHallCount(parentRegion.getMainHallCount()-region.getMainHallCount());
			parentRegion.setShareChannelCount(parentRegion.getShareChannelCount()-region.getShareChannelCount());
			parentRegion.setSpecialAgentCount(parentRegion.getSpecialAgentCount()-region.getSpecialAgentCount());
			parentRegion.setTelecomHallCount(parentRegion.getTelecomHallCount()-region.getTelecomHallCount());
			parentRegion.setUnicomHallCount(parentRegion.getUnicomHallCount()-region.getUnicomHallCount());
			parentRegion.setVillagePointCount(parentRegion.getVillagePointCount()-region.getVillagePointCount());
			this.regionDao.updateRegions(parentRegion);
			
			this.regionDao.delRegions(id);
			LoggerUtil.LogWarn("删除微区域:"+region.getName());
			out.print("{\"result\":true}");
			out.flush();
			out.close();
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	
	public void addRegion(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			request.setCharacterEncoding("UTF-8");
			String name = URLDecoder.decode(String.valueOf(request.getParameter("name")),"UTF-8");
			Integer parentRegionId = Integer.parseInt(request.getParameter("parentRegionId"));
			Regions region = new Regions();
			region.setName(name);
			region.setParentRegionId(parentRegionId);
			region.setAuthorizedPointCount(0);
			region.setCooperativeHallCount(0);
			region.setMainHallCount(0);
			region.setShareChannelCount(0);
			region.setSpecialAgentCount(0);
			region.setTelecomHallCount(0);
			region.setUnicomHallCount(0);
			region.setVillagePointCount(0);
			this.regionDao.addRegions(region);
			LoggerUtil.LogInfo("增加微区域:"+region.getName());
			out.print("{\"result\":true}");
			out.flush();
			out.close();
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	
	public void editRegion(){
		HttpServletResponse response = Struts2Util.getResponse();
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			out = (PrintWriter) response.getWriter();
			HttpServletRequest request = Struts2Util.getRequest();
			request.setCharacterEncoding("UTF-8");
			String name = URLDecoder.decode(String.valueOf(request.getParameter("name")),"UTF-8");
			Integer id = Integer.parseInt(request.getParameter("id"));
			Regions region = this.regionDao.getRegionsById(id);
			region.setName(name);
			this.regionDao.updateRegions(region);
			LoggerUtil.LogInfo("更新微区域:"+region.getName());
			out.print("{\"result\":true}");
			out.flush();
			out.close();
		} catch (Exception e) {
			out.print("{\"result\":false}");
			out.flush();
			out.close();
			e.printStackTrace();
		}
	}
	/**
	 * @return the regionDao
	 */
	public IRegionsDAO getRegionDao() {
		return regionDao;
	}

	/**
	 * @param regionDao the regionDao to set
	 */
	public void setRegionDao(IRegionsDAO regionDao) {
		this.regionDao = regionDao;
	}

	/**
	 * @return the gridDao
	 */
	public IGridDAO getGridDao() {
		return gridDao;
	}

	/**
	 * @param gridDao the gridDao to set
	 */
	public void setGridDao(IGridDAO gridDao) {
		this.gridDao = gridDao;
	}

}
